package managedbean;


import java.io.Serializable;
import java.util.*;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.*;
import javax.faces.context.FacesContext;
import javax.naming.Context;
import javax.naming.InitialContext;

import jpa.CustomerJPA;
import ejb.OrderFacadeRemote;


/**
 * Managed Bean TotalAmountByCustomerMBean
 */
@ManagedBean(name = "totalOrders")
@SessionScoped
public class TotalOrdersByCustomerMBean implements Serializable {

	private static final long serialVersionUID = 1L;	
	
	@EJB
	private OrderFacadeRemote orderFR;
	protected int totalOrders;
	protected CustomerJPA customer;
	private boolean list=false;
	private boolean consult=false;

	public TotalOrdersByCustomerMBean() throws Exception  {
		ListTotalOrders();
	}
	
	
	public TotalOrdersByCustomerMBean(CustomerJPA customer) throws Exception {
		this.customer=customer;
		ListTotalOrdersCustomer(customer);
	}
		
	public int getTotalOrders() {
		return totalOrders;
	}

	public CustomerJPA getCustomer() {
		return customer;
	}

	public String ListTotalOrders() throws Exception {
		try {
			FacesContext fc = FacesContext.getCurrentInstance();
			String customerId = getCustomerId(fc);
			if (customerId=="") {
				FacesMessage msg = new FacesMessage( "You need to inform a NIF");
				FacesContext.getCurrentInstance().addMessage(null, msg);
			}
			if(getList(fc).equals("true")) list=true;
			else consult=true;
			ShowClientMBean sc = new ShowClientMBean(customerId);
			customer=sc.getDataCustomer();
			Orders(customer);
			return "TotalOrdersByCustomerView";
		}
		catch (Exception e) {
			e.printStackTrace();
			FacesMessage msg = new FacesMessage( "Incorrect NIF");
			FacesContext.getCurrentInstance().addMessage(null, msg);
			return "ErrorView";
		}
	}
	
	public String ListTotalOrdersCustomer(CustomerJPA customer) throws Exception {
		this.customer=customer;
		totalOrders = Orders(customer);
		return "TotalOrdersByCustomerView";
	}
	
	public String getCustomerId(FacesContext fc){
 		Map<String,String> params = fc.getExternalContext().getRequestParameterMap();
 		return (params.get("idCustomer"));
 	}
	

	public String getList(FacesContext fc){
 		Map<String,String> params = fc.getExternalContext().getRequestParameterMap();
 		return (params.get("list"));
 	}
	
	@SuppressWarnings("unchecked")
	public int Orders(CustomerJPA customer) throws Exception {	
		Properties props = System.getProperties();
		Context ctx = new InitialContext(props);
		orderFR = (OrderFacadeRemote) ctx.lookup("java:app/PracticalCaseStudyJEE.jar/OrderFacadeBean!ejb.OrderFacadeRemote");
		totalOrders = (int) orderFR.orders(customer);
		return totalOrders;
		
	}
	
	public boolean isConsult() {
		return consult;
	}
	public boolean isList() {
		return list;
	}
}
